<?php

namespace app\admin\model\survey;

use app\admin\model\facrm\Customer;
use app\admin\model\User;
use think\Model;


class Records extends Model
{

    

    

    // 表名
    protected $name = 'survey_records';
    
	// 自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'add_time';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'add_time_text'
    ];
    

    



    public function getAddTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['add_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setAddTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


	public static function getLastIdByCustomer($customer_id){
		return self::where(['customer_id' => $customer_id,'is_del' => 0])->order('add_time desc')->limit(1)->value('id');
	}

	public static function getCountByCustomer($customer_id){
		return self::where(['customer_id' => $customer_id,'is_del' => 0])->count();
	}

	public function customer(){
		return $this->belongsTo(Customer::class, 'customer_id', 'id')->setEagerlyType(0);
	}

	public function user(){
		return $this->belongsTo(User::class, 'uid', 'uid')->setEagerlyType(0);
	}

	public function answer(){
		return $this->hasMany(RecordsAnswer::class,'records_id','id');
	}

	public function getResultAttr($value){
		return $value ? json_decode($value,true) : [];
	}
}
